<template>
  <div class="play-body">
    <el-row justify="space-between">
      <el-col :span="10" class="flex-left">
        <el-button @click.stop="showPlayWin">
          <i-bi-chevron-down/>
        </el-button>
        <el-button @click="winSize('window-max')">
          <i-bi-arrows-angle-expand/>
        </el-button>
      </el-col>
      <el-col :span="10" class="flex-right">
        <div class="right">
          <el-icon @click="winSize('window-min')">
            <i-bi-dash-lg />
          </el-icon>
          <el-icon @click="winSize('window-max')">
            <i-bi-app />
          </el-icon>
          <el-icon @click="winSize('window-close')">
            <i-bi-x-lg />
          </el-icon>
        </div>
      </el-col>
    </el-row>
    <el-row justify="space-around">
      <el-col :span="10" class="disc-container">
        <div class="disc" :class="{ 'disc-playing': isPlaying }">
          <!-- 唱针 -->
          <div class="stylus" :class="{ 'stylus-playing': isPlaying }">
            <img src="@/assets/img/stylus.png" alt="stylus">
          </div>
          <!-- 唱片 -->
          <div class="disc-plate">
            <img class="disc-bg" src="@/assets/img/disc_bg.png" alt="disc">
            <img class="album-cover" :src="currentSong?.albumPic" alt="cover">
          </div>
        </div>
      </el-col>
      <el-col :span="10">
        <div class="lyrics-container">
          <div class="lyrics" v-if="lyricObj.length" :style="transform">
            <p :class="[isCurLyric(index)]" v-for="(item, index) in lyricObj" :key="index">{{item.txt}}</p>
          </div>
          <div v-else class="lyric-empty">
            <p v-if="lyric">纯音乐，无歌词</p>
            <p v-else>歌词加载中......</p>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { defineEmits, reactive, onMounted, watch, computed, toRefs } from "vue";
import { lyrics } from "@/assets/apis/http";
import { usePlayStore } from '@/store/PlayStore'

const props = defineProps({
  sId: {
    type: [Number, String],
    default: 0
  },
  currentTime: {
    type: Number,
    default: 0
  }
});

const playStore = usePlayStore()
const isPlaying = computed(() => playStore.isPlayed)
const currentSong = computed(() => playStore.currentSong)

interface lyricactive{
  t: number,
  txt:string
}
const emit = defineEmits();
const info = reactive({
  lyric: false,
  lyricObj: <lyricactive[]>[],
  curIndex: 0,
  isFull: false
});
// Methods
async function getLyrics (id)  {
  const { lrc } = await lyrics({id:id})
  console.log(id+"获取歌词信息",lrc)
  formatLyric(lrc);
}

const formatLyric = (lrc) => {
  const lrcReg = /^\[(\d{2}):(\d{2}.\d{2,})\]\s*(.+)$/;
  if (!lrc.lyric) {
    info.lyric = true;
    return;
  }

  const lyricLis = lrc.lyric.split('\n');
  info.lyric = lrc.lyric;
  info.lyricObj = [];  // 清空之前的歌词

  lyricLis.forEach(item => {
    const arr = lrcReg.exec(item);
    if (!arr) return;
    // 转换为毫秒
    const time = (Number(arr[1]) * 60 + Number(arr[2])) * 1000;
    info.lyricObj.push({ t: time, txt: arr[3] });
  });

  // 根据时间轴重排顺序
  info.lyricObj.sort((a, b) => a.t - b.t);
  console.log("歌词信息", info.lyricObj);
};
const isCurLyric = computed(() => {
  return (index) => {
    // console.log("当前高亮的歌词",index,info.curIndex,props.currentTime)
    return index === info.curIndex && props.currentTime ? 'active' : '';
  };
});
// Lifecycle hooks
onMounted(() => {
  getLyrics(props.sId);
});
const transform = computed(() => {
  // 计算滚动位置，使当前歌词保持在中间
  const lineHeight = 42; // 每行歌词高度
  // 计算容器中点位置
  const containerHeight = window.innerHeight * 0.8; // 80vh
  const middlePosition = containerHeight / 2 - lineHeight / 2; // 减去半行高，使歌词完全居中
  
  // 计算当前歌词应该在的位置
  const offset = middlePosition - (info.curIndex * lineHeight) - lineHeight * 6; // 向上偏移3行
  
  return `transform: translateY(${offset}px)`;
});
watch(() => props.sId, (newVal) => {
  info.lyric = false;
  info.lyricObj = [];
  info.curIndex = 0;
  getLyrics(newVal);
});

watch(() => props.currentTime, (newVal) => {
  // 无歌词的时候不做动画滚动
  if (!info.lyricObj.length) return;
  console.log("当前歌词时间戳", newVal);
  // 找到当前时间对应的歌词索引
  info.curIndex = findCurIndex(newVal);
  // 只有在有效索引时才显示歌词
  if (info.curIndex >= 0) {
    console.log("当前歌词索引", info.curIndex, "歌词内容", info.lyricObj[info.curIndex]?.txt);
  }
});
const findCurIndex = (time) => {
  // 遍历查找当前时间对应的歌词
  for (let i = 0; i < info.lyricObj.length; i++) {
    // 如果是最后一句歌词
    if (i === info.lyricObj.length - 1) {
      // 如果当前时间大于最后一句歌词的时间，返回最后一句
      return time >= info.lyricObj[i].t ? i : i - 1;
    }
    
    const curTime = info.lyricObj[i].t;
    const nextTime = info.lyricObj[i + 1].t;
    
    if (time >= curTime && time < nextTime) {
      return i;
    }
  }
  // 如果时间小于第一句歌词的时间，返回-1
  return time < info.lyricObj[0]?.t ? -1 : 0;
};
function showPlayWin(){
  console.log("调用父组件方法")
  emit('tiggerPlayWin')
}

function winSize(type: string) {
  window.electron.ipcRenderer.send(type);
}
const {lyricObj} = toRefs(info);
</script>
<style lang="scss" scoped>
.play-body{
  .flex-left {
    display: flex;
    justify-content: flex-start;
    .ep-button{
      background-color: transparent;
      color: white;
    }
  }
  .flex-right{
    display: flex;
    justify-content: flex-end;
    .right{
      font-size: 22px;
      i{
        padding-left: 10px;
      }
    }
  }
}
.disc-container {
  position: relative;
  padding: 20px;
  height: 80vh;
  display: flex;
  align-items: center;
  
  .disc {
    width: 100%;
    position: relative;
    
    &.disc-playing {
      .disc-plate {
        animation: rotate 20s linear infinite;
      }
    }
    
    .stylus {
      position: absolute;
      top: -50px;
      left: 50%;
      transform-origin: 15px 15px;
      transform: rotate(-70deg);
      transition: transform 0.3s ease-in-out;
      z-index: 1;
      
      &.stylus-playing {
        transform: rotate(-50deg);
      }
      
      img {
        width: auto;
        height: auto;
      }
    }
    
    .disc-plate {
      position: relative;
      width: 300px;
      height: 300px;
      margin: 0 auto;
      animation-play-state: paused;
      border-radius: 50%;
      overflow: hidden;
      
      .disc-bg {
        position: absolute;
        width: 100%;
        height: 100%;
      }
      
      .album-cover {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 190px;
        height: 190px;
        transform: translate(-50%, -50%);
        border-radius: 50%;
      }
    }
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.lyrics-container {
  height: 80vh;
  overflow: hidden;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.lyrics {
  font-size: 0;
  transform: translateY(0);
  transition: transform 1.5s ease-in-out;
  width: 100%;
  text-align: center;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  padding-top: 40vh; // 调整顶部内边距

  :deep(p) {
    margin: 0;
    line-height: 42px;
    font-size: 16px;
    font-weight: 300;
    transition: all 0.3s;
    padding: 0 20px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;

    &.active {
      color: var(--el-color-primary);
      font-size: 20px;
      font-weight: 500;
      transform: scale(1.05); // 稍微减小放大比例
      text-shadow: 0 0 10px var(--el-color-primary-light-5); // 添加发光效果
    }

    &:hover {
      color: var(--el-color-primary-light-3);
    }
  }
  
  // 添加底部内边距，确保最后一行歌词可以滚动到中间
  &::after {
    content: '';
    display: block;
    height: 40vh; // 调整底部内边距
  }
}

.lyric-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  min-height: 100px;
  font-size: 16px;
  color: var(--el-text-color-secondary);
}
</style>
